//
//  BKGDManagerViewController.m
//  bestkeep
//
//  Created by 武探 on 2016/11/9.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKGDManagerViewController.h"
#import "BKGDMainViewController.h"
#import "BKGDWebViewController.h"
#import "BKGDEvaluationViewController.h"
#import "BKGDManagerTitleView.h"
#import "BKGDPageScrollView.h"

NSString *const BKGDManagerViewControllerMoveToPageNotificationKey = @"BKGDManagerViewControllerMoveToPageNotificationKey";

NSString *const BKGDManagerViewCellIdentifier = @"BKGDManagerViewCellIdentifier";

@interface BKGDManagerViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, BKGDManagerTitleViewDelegate, BKGDMainViewControllerDelegate>

@property(nonatomic,strong) BKGDManagerTitleView *titleView;

@property(nonatomic,strong) UICollectionView *collectionView;

@property(nonatomic,strong) BKGDPageScrollView *pageScrollView;

@property(nonatomic,strong) BKGDMainViewController *detailController;
@property(nonatomic,strong) BKGDWebViewController *webController;
@property(nonatomic,strong) BKGDEvaluationViewController *evaluationController;

@end

@implementation BKGDManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeComponent];
}

-(void)initializeComponent {
//    self.title = @"商品详情";
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _titleView = [[BKGDManagerTitleView alloc] init];
    _titleView.titles = @[BKGDLocalizedString(@"BKGDManagerTitlesGoods"), BKGDLocalizedString(@"BKGDManagerTitlesDetail"), BKGDLocalizedString(@"BKGDManagerTitlesEvaluation")];
    _titleView.delegate = self;
    
//    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"BKGDShare"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonTouch)];
//    rightBarButton.enabled = NO;
//    self.navigationItem.rightBarButtonItem = rightBarButton;
//    [self.navigationItem.rightBarButtonItem setImageInsets:UIEdgeInsetsMake(0, -15, 0, 5)];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 28, 23);
    UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"BKGDShare"]];
    imageView.frame = CGRectMake(5, 0, 23, 23);
    [rightBtn addSubview:imageView];
    [rightBtn addTarget:self action:@selector(rightBarButtonTouch) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    [self addchildViewControllers];
    
    CGRect bounds = self.view.bounds;
    _pageScrollView = [[BKGDPageScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(bounds), CGRectGetHeight(bounds))];
    [_pageScrollView setSubview:_detailController.view toPageIndex:0];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.bounces = NO;
    _collectionView.scrollEnabled = NO;
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:BKGDManagerViewCellIdentifier];
    [self.view addSubview:_collectionView];
    
    [self makeConstraints];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollToPageNotification:) name:BKGDManagerViewControllerMoveToPageNotificationKey object:nil];
}

-(void)makeConstraints {
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsZero);
    }];
}

-(void)addchildViewControllers {
    
    CGRect bounds = self.view.bounds;
    
    UIEdgeInsets contentInset = UIEdgeInsetsMake(64, 0, 49, 0);
    
    _detailController = [[BKGDMainViewController alloc] init];
    [self addChildViewController:_detailController];
    _detailController.delegate = self;
    _detailController.goodsId = _goodsId;
    _detailController.saleTypes = _saleTypes;
    _detailController.thnormaltype = _thnormaltype;
    _detailController.storeId = _storeId;
    _detailController.shopKeeper = _shopKeeper;
    _detailController.goodsCoverImg = _goodsCoverImg;
    _detailController.view.frame = bounds;
    UIEdgeInsets dci = _detailController.contentInsets;
    dci.bottom += contentInset.bottom;
    dci.top += contentInset.top;
    _detailController.contentInsets = dci;
    UIEdgeInsets dsci = _detailController.scrollIndicatorInsets;
    dsci.bottom += contentInset.bottom;
    dsci.top += contentInset.top;
    _detailController.scrollIndicatorInsets = contentInset;
    
    _webController = [[BKGDWebViewController alloc] init];
    [self addChildViewController:_webController];
    _webController.view.frame = bounds;
    _webController.contentInset = contentInset;
    
    _evaluationController = [[BKGDEvaluationViewController alloc] init];
    [self addChildViewController:_evaluationController];
    _evaluationController.goodsId = _goodsId;
    _evaluationController.view.frame = bounds;
    _evaluationController.contentInset = contentInset;
    
    __weak typeof(self) weakSelf = self;
    
    _webController.headerRefreshCallback = ^ {
        if(!weakSelf) {
            return;
        }
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        strongSelf.navigationItem.titleView = strongSelf.titleView;
        strongSelf.collectionView.scrollEnabled = YES;
        
        [strongSelf.pageScrollView previousPage];
        [strongSelf.webController allowHeaderRefresh:NO];
    };
}

#pragma -mark rightBarButton 
-(void)rightBarButtonTouch {
    [_detailController share];
}

#pragma -mark collectionView delegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.childViewControllers.count;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = collectionView.bounds.size;
    return size;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:BKGDManagerViewCellIdentifier forIndexPath:indexPath];
    
    NSArray *array = [cell.contentView subviews];
    for (UIView *view in array) {
        [view removeFromSuperview];
    }
    
    if(SystemVersion < 8.0) {
        [self displayCell:cell atIndexPath:indexPath];
    }
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    [self displayCell:cell atIndexPath:indexPath];
}

-(void)displayCell:(UICollectionViewCell*)cell atIndexPath:(NSIndexPath*)indexPath {
    
    NSArray *subviews = cell.contentView.subviews;
    for (UIView *view in subviews) {
        [view removeFromSuperview];
    }
    
    UIView *view;
    
    switch (indexPath.row) {
        case 0:
        {
            view = _pageScrollView;
        }
            break;
        case 1:
        {
            view = _webController.view;
            _webController.baseURLString = _detailController.goodsDetail.goodsDetailedUrl;
        }
            break;
        default:
        {
            view = _evaluationController.view;
        }
    }
    
    [cell.contentView addSubview:view];
}

#pragma -mark titleView delegate

-(void)titleView:(BKGDManagerTitleView *)view didSelectedAtIndex:(NSInteger)index {
    
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
}

-(NSInteger)getScrollPage:(UIScrollView*)scrollView {
    
    CGFloat offsetX = scrollView.contentOffset.x;
    NSInteger page = offsetX / CGRectGetWidth(scrollView.bounds);
    return page;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger page = [self getScrollPage:scrollView];
    [_titleView setCurrentIndex:page];
}

#pragma -mark BKGDViewController delegate

-(void)BKGDFooterRefreshing {
    self.navigationItem.titleView = nil;
    self.title = BKGDLocalizedString(@"BKGDMainTitle");
    self.collectionView.scrollEnabled = NO;
    
    self.webController.baseURLString = self.detailController.goodsDetail.goodsDetailedUrl;
    
    [self.pageScrollView nextPage];
    [self.pageScrollView setSubview:self.webController.view toPageIndex:1];
    [self.webController allowHeaderRefresh:YES];
}

-(void)BKGDRequestCompleted {
    
    self.navigationItem.rightBarButtonItem.enabled = YES;
    self.navigationItem.titleView = self.titleView;
    self.collectionView.scrollEnabled = YES;
}

-(void)scrollToPageNotification:(NSNotification*)notification {
    id obj = notification.object;
    if(!obj && ![obj isKindOfClass:[NSNumber class]]) {
        return;
    }
    
    NSInteger index = [obj integerValue];
    if(index > self.titleView.titles.count - 1) {
        return;
    }
    
    [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    [_titleView setCurrentIndex:index];
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
